package com.jetpack.mvvm.lib.base.extention

import androidx.activity.ComponentActivity
import androidx.annotation.MainThread
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelLazy
import androidx.lifecycle.ViewModelStoreOwner
import com.jetpack.mvvm.lib.base.interf.AppShareVMSupport

/**
 * 通过 ComponentActivity 的扩展函数 appViewModules 获取全局 viewModel
 */
@MainThread
inline fun <reified VM : ViewModel> ComponentActivity.appViewModules(): Lazy<VM> {
    return ViewModelLazy(
        VM::class,
        {
            if (this.application !is AppShareVMSupport) {
                throw IllegalStateException(
                    "Your Application should implements AbleShareVM"
                )
            }
            if ((this.application as AppShareVMSupport).getShareViewModelDel() !is ViewModelStoreOwner) {
                throw IllegalStateException(
                    "The subclass of ShareViewModelInterface should implements ViewModelStoreOwner"
                )
            }
            ((this.application as AppShareVMSupport).getShareViewModelDel() as ViewModelStoreOwner).viewModelStore
        },
        { (this.application as AppShareVMSupport).getShareViewModelDel().getViewModelFactory() })
}

/**
 * 通过 androidx.fragment.app.Fragment 的扩展函数 appViewModules 获取全局 viewModel
 */
@MainThread
inline fun <reified VM : ViewModel> Fragment.appViewModules(): Lazy<VM> {
    return ViewModelLazy(
        VM::class,
        {
            if (this.requireActivity().application !is AppShareVMSupport) {
                throw IllegalStateException(
                    "Your Application should implements AbleShareVM"
                )
            }
            if ((this.requireActivity().application as AppShareVMSupport).getShareViewModelDel() !is ViewModelStoreOwner) {
                throw IllegalStateException(
                    "The subclass of ShareViewModelInterface should implements ViewModelStoreOwner"
                )
            }
            ((this.requireActivity().application as AppShareVMSupport).getShareViewModelDel() as ViewModelStoreOwner).viewModelStore
        },
        { (this.requireActivity().application as AppShareVMSupport).getShareViewModelDel().getViewModelFactory() })
}